package xyz.penghaonan.p2plib.job.operations;

import android.net.wifi.p2p.WifiP2pDevice;

import androidx.annotation.NonNull;

import java.util.Collection;

import xyz.penghaonan.p2plib.utils.P2PActionListener;
import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.job.base.BaseOperation;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PHelper;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PListener;
import xyz.penghaonan.p2plib.helper.p2phelper.WifiP2PListenerAdapter;

public class ScanServerOperation extends BaseOperation<Collection<WifiP2pDevice>> {

    private final WifiP2PListener p2pListener = new WifiP2PListenerAdapter() {
        @Override
        public void onPeersAvailable(@NonNull Collection<WifiP2pDevice> wifiP2pDeviceList) {
            super.onPeersAvailable(wifiP2pDeviceList);
            log("onPeersAvailable count:" + wifiP2pDeviceList.size());
            for (WifiP2pDevice device : wifiP2pDeviceList) {
                log("onPeersAvailable device:" + device);
            }
            Result<Collection<WifiP2pDevice>> result = new Result<>();
            result.success = wifiP2pDeviceList.size() > 0;
            result.data = wifiP2pDeviceList;
            setResult(result);
            if (result.success) {
                operationContinue();
            }
        }
    };

    @Override
    public void doOperation() {
        notifyProgress(0.2f, "扫描服务端");
        WifiP2PHelper p2PHelper = P2PManager.getP2PHelper();
        p2PHelper.addListener(p2pListener);
        p2PHelper.discover(new P2PActionListener() {
            @Override
            public void onSuccess() {
                super.onSuccess();
                log("discover onSuccess");
                notifyProgress(0.8f, "扫描服务端成功");
            }

            @Override
            public void onFailure(int reason) {
                super.onFailure(reason);
                notifyProgress(0.8f, "扫描服务端失败:" + reason);
                log("discover onFailure reason:" + reason);
            }
        });
        operationWait(10000);
        p2PHelper.removeListener(p2pListener);
    }

    @Override
    public String getName() {
        return "扫描服务端";
    }
}
